<template>
  <div class="app-container">
    <el-row style="margin-bottom: 24px">
      <el-col :span="8"
        ><div class="flex flex-column align-center">
          <div class="title">楼栋总数</div>
          <div class="total">{{ Statistics.buildingNumber }}栋</div>
        </div></el-col
      >
      <el-col :span="8"
        ><div class="flex flex-column align-center both-border">
          <div class="title">单元总数</div>
          <div class="total">{{ Statistics.unitNumber }}个</div>
        </div></el-col
      >
      <el-col :span="8"
        ><div class="flex flex-column align-center">
          <div class="title">房间总数</div>
          <div class="total">{{ Statistics.houseNumber }}间</div>
        </div></el-col
      >
    </el-row>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="楼盘名称" prop="estateName">
        <el-input
          v-model="queryParams.estateName"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼栋名称" prop="buildingName">
        <el-input
          v-model="queryParams.buildingName"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="楼盘地址" prop="premisesAddress">
        <el-input
          v-model="queryParams.premisesAddress"
          placeholder="请输入地址"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物业" prop="buildingNumber">
        <el-select
          v-model="queryParams.status"
          placeholder="物业"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in []"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
          >新建</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="buildingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="楼栋编号" prop="buildingId" width="120" />
      <el-table-column
        label="楼盘"
        prop="estateName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="地址"
        prop="premisesAddress"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="楼栋"
        prop="buildingName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="分布类型" prop="estateType" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_estate_type"
            :value="scope.row.estateType"
          />
        </template>
      </el-table-column>
      <el-table-column label="单元数" prop="unitNumber" width="100" />
      <el-table-column label="房间数" prop="houseNumber" width="100" />
      <el-table-column label="所属物业" prop="propertyName" width="100" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.estateId !== 1">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
            >管理楼栋</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 新建楼栋start -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="地区" prop="region">
          <el-cascader
            v-if="open"
            ref="areaPicker"
            v-model="form.region"
            :props="areaProps"
            :show-all-levels="false"
            @change="handleChangeArea"
            style="width: 240px"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="楼盘" prop="estateName">
          <el-select
            v-model="form.estateId"
            @change="estateChange"
            placeholder="请选择楼盘"
            clearable
            style="width: 240px"
            @visible-change="checkedRegion"
          >
            <el-option
              v-for="dict in estateList"
              :key="dict.estateId"
              :label="dict.estateName"
              :value="dict.estateId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="楼栋名称" prop="buildingName">
          <el-input
            v-model="form.buildingName"
            placeholder="请输入名称"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="单元" prop="unitList">
          <i
            class="el-icon-circle-plus"
            style="
              color: #66b1ff;
              font-size: 24px;
              cursor: pointer;
              margin-left: 8px;
            "
            @click="addUnit"
          ></i>
        </el-form-item>
        <el-row
          v-for="(item, index) in form.unitList"
          :key="index"
          :gutter="10"
          style="margin: 10px 0"
        >
          <el-col :span="11">
            单元名称：
            <el-input
              v-model="item.unitName"
              placeholder="请输入单元名称"
              style="width: 240px"
            />
          </el-col>
          <el-col :span="11">
            层数：
            <el-input
              v-model.number="item.floors"
              type="number"
              placeholder="请输入楼层"
              style="width: 240px"
            />
          </el-col>
          <el-col :span="2" style="display: flex; align-items: center">
            <i
              class="el-icon-remove-outline"
              style="
                color: #e63f32;
                font-size: 24px;
                margin-left: 20px;
                margin-top: 6px;
                cursor: pointer;
              "
              @click="delUnit(index, item)"
            ></i>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBuilding,
  getBuilding,
  delBuilding,
  getBuildingStatistics,
  listEstate,
  addBuilding,
  editBuilding,
  delUnit,
} from "@/api/house/estate";
import { listArea } from "@/api/system/config";
export default {
  name: "Estate",
  dicts: ["dict_estate_type", "sys_normal_disable"],
  watch: {
    "form.region"(newVal, oldVal) {
      this.form.provinceId = newVal[0];
      this.form.cityId = newVal[1];
      this.form.districtId = newVal[2];
      this.form.streetId = newVal[3];
      this.form.communityId = newVal[4];
    },
  },
  data() {
    const validateUnit = (rule, value, callback) => {
      if (
        value.some((e) => {
          return e.unitName == "";
        })
      ) {
        callback(new Error("请填写单元"));
      } else {
        callback();
      }
    };
    return {
      value: "",
      //统计数据
      Statistics: {
        estateNumber: 0,
        buildingNumber: 0,
        houseNumber: 0,
      },
      locationDialog: false, //坐标弹窗
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      buildingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      //区域
      options: [],
      estateList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        estateName: undefined,
        roleKey: undefined,
        status: undefined,
      },
      // 表单参数
      form: {
        region: [],
        estateName: "", //楼盘名称
        provinceId: "", //省
        cityId: "", //市
        districtId: "", //区
        streetId: "", //所属街道
        communityId: "", //所属社区
        premisesAddress: "光明2路", //小区地址
        buildingName: "", //楼栋名称
        unitList: [
          {
            unitName: "",
            floors: null,
          },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        estateName: [
          { required: true, message: "楼盘不能为空", trigger: "change" },
        ],
        buildingName: [
          { required: true, message: "楼栋名称不能为空", trigger: "change" },
        ],
        region: [
          { required: true, message: "区域不能为空", trigger: "change" },
        ],
        unitList: [
          {
            required: true,
            trigger: "change",
            validator: validateUnit,
          },
        ],
      },
      areaProps: {
        lazy: true,
        // emitPath: false,
        lazyLoad(node, resolve) {
          listArea({ level: node.level + 1, parentId: node.value }).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 4,
              }));
              resolve(areas);
            }
          );
        },
      },
    };
  },
  created() {
    this.getList();
    this.getStatistics();
  },
  methods: {
    //检测是否选择区域
    checkedRegion(e) {
      if (this.form.communityId == undefined && e) {
        this.$modal.closeAll();
        this.$modal.msgError("请选择地区");
      }
    },
    //区域选择
    handleChangeArea(val) {
      const checkedNode = this.$refs["areaPicker"].panel.getNodeByValue(val);
      const ids = checkedNode.path;
      const labels = checkedNode.pathLabels;
      this.form.provinceName = labels[0];
      this.form.cityName = labels[1];
      this.form.districtName = labels[2];
      this.form.streetName = labels[3];
      this.form.communityName = labels[4];
      this.getlistEstate();
    },
    //删除单元
    delUnit(index, item) {
      if (item.unitId) {
        this.$modal
          .confirm("是否确认删除该单元")
          .then(function () {
            return delUnit(item.unitId);
          })
          .then(() => {
            this.form.unitList.splice(index, 1);
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      }else{
        this.form.unitList.splice(index, 1);
      }

    },
    //增加单元
    addUnit() {
      this.form.unitList.push({
        unitName: "",
        floors: null,
      });
    },
    //坐标拾取器回调方法
    selectLocation(e) {
      this.form.longitude = e.lng;
      this.form.latitude = e.lat;
      this.locationDialog = false;
    },
    /** 查询统计数据 */
    getStatistics() {
      this.loading = true;
      getBuildingStatistics().then((response) => {
        this.Statistics = response.data;
        this.loading = false;
      });
    },
    /** 查询楼盘列表 */
    getlistEstate() {
      let param = {
        pageNum: 1,
        pageSize: 999,
        communityId: this.form.region[4],
      };
      listEstate(param).then((response) => {
        this.estateList = response.rows;
      });
    },
    /** 查询楼栋列表 */
    getList() {
      this.loading = true;
      listBuilding(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.buildingList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        region: [],
        estateName: "", //楼盘名称
        provinceId: "", //省
        cityId: "", //市
        districtId: "", //区
        streetId: "", //所属街道
        communityId: "", //所属社区
        premisesAddress: "", //小区地址
        buildingName: "", //楼栋名称
        unitList: [
          {
            unitName: "",
            floors: null,
          },
        ],
      };

      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.buildingId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建楼栋";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const buildingId = row.buildingId || this.ids;
      getBuilding(buildingId).then((response) => {
        let form = response.data;
        let region = [];
        region.push(response.data.provinceId);
        region.push(response.data.cityId);
        region.push(response.data.districtId);
        region.push(response.data.streetId);
        region.push(response.data.communityId);
        form.region = region;
        this.open = true;
        this.$nextTick(() => {
          this.form = form;
          this.getlistEstate();
        });
        this.title = "编辑";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.buildingId) {
            editBuilding(this.form).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBuilding(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const buildingId = row.buildingId || this.ids;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          return delBuilding(buildingId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/enterprise/house/building/export",
        {
          ...this.queryParams,
          buildingIds:this.ids
        },
        `楼栋_${new Date().getTime()}.xlsx`
      );
    },
    estateChange(e) {
      let data = this.estateList.find((item) => item.estateId === e);
      this.form.estateName = data.estateName;
    },
  },
};
</script>
<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}
.total {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}
.both-border {
  border-left: 1px solid #999;
  border-right: 1px solid #999;
}
</style>
